package com.songxh.facade.controller;

import com.songxh.core.base.CommonResult;
import com.songxh.core.utils.QINIUUploadFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * 图片上传
 *
 * @author songxh
 * @create 2023-01-16-11:01
 */
@RestController
@RequestMapping("/gra/songxh/image")
public class ImageUploadController {

    @Autowired
    private QINIUUploadFileUtils qiniuUploadFileUtils;

    @PostMapping("/upload")
    public CommonResult imageUpload(@RequestParam("file") MultipartFile file) {
        //获取原始文件名称 比如 abc.jpg，用于获取后缀
        String originalFilename = file.getOriginalFilename();
        //做唯一文件名
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //上传到七牛云
        String name = qiniuUploadFileUtils.uploadFile(file, fileName);
        if (name == null) {
            CommonResult.failure("图片上传失败");
        }
        return CommonResult.success(name);
    }

    /**
     * 获取图片
     * @param imageName
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/download/{imageName}")
    public CommonResult imageDownload(@PathVariable("imageName") String imageName, HttpServletResponse response) throws IOException {
        String downloadUrl = qiniuUploadFileUtils.download(imageName);
        URL url = new URL(downloadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //设置请求方式
        connection.setRequestMethod("GET");
        //设置超时时间 10秒
        connection.setConnectTimeout(1000 * 10);
        InputStream inputStream = connection.getInputStream();
        ServletOutputStream outputStream = response.getOutputStream();
        //设置文件类型
        response.setContentType("image/jpeg");
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        //关闭资源
        outputStream.close();
        inputStream.close();
        return CommonResult.success();
    }
}
